package com.gudaomai.ekproject.service.impl;

import com.baomidou.mybatisplus.toolkit.IdWorker;
import com.gudaomai.ekproject.common.CommonConstant;
import com.gudaomai.ekproject.common.CommonException;
import com.gudaomai.ekproject.common.MsgConstant;
import com.gudaomai.ekproject.entity.Permission;
import com.gudaomai.ekproject.entity.Role;
import com.gudaomai.ekproject.entity.RolesPermissions;
import com.gudaomai.ekproject.mapper.RolesPermissionsMapper;
import com.gudaomai.ekproject.service.IRolesPermissionsService;
import com.gudaomai.ekproject.service.impl.BaseServiceImpl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Service;

/**
 * <p>
 * roles_permissions 服务实现类
 * </p>
 *
 * @author zenghualu
 * @since 2017-06-26
 */
@Service
public class RolesPermissionsServiceImpl extends BaseServiceImpl<RolesPermissionsMapper, RolesPermissions>
		implements IRolesPermissionsService {

	/**
	 * TODO:complete 添加相应角色的权限 1.check是否角色权限已经存在 如果已经存在抛异常 2.追加
	 */
	@Autowired
	protected MessageSource messageSource;
	@Autowired
	RolesPermissionsMapper rolesPermissionsMapper;
	@Autowired
	RoleServiceImpl roleServ;
	@Autowired
	PermissionServiceImpl permissionServ;

	//添加角色权限
	public void add(Role role, Permission perm) throws CommonException {

		// 查找当前数据库是否存在该条记录

		RolesPermissions rolesPermissions = rolesPermissionsMapper.getRolesPermissionsByPidRid(perm.getId(),
				role.getId());

		Role roleTemp = roleServ.selectById(role);
		Permission permissionTemp = permissionServ.selectById(perm);

		// 存在，抛出异常，并退出程序执行
		if (null == roleTemp || null == permissionTemp || rolesPermissions != null) {
			throw new CommonException(CommonConstant.RESULT_CODE_CREATED,
					getMessage(MsgConstant.RET_ROLES_PERMISSIONS_ADD_ALREADY_EXIST));
		}

		// 不存在，则执行插入操作
		RolesPermissions rPermissions = new RolesPermissions();
		rPermissions.setId(IdWorker.get32UUID());
		// 使用IDworker获取32UUID
		// 源码：java.util.UUID.randomUUID().toString().replace("-","");
		rPermissions.setRoleId(role.getId());
		rPermissions.setPermissionId(perm.getId());

		// 插入该条记录
		this.insert(rPermissions);

	}

}
